package com.medvalley.tcm.weixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.medvalley.tcm.cache.GuavaCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * Created by linsong on 2018/3/18.
 */

@Component
public class JSApiTicket extends WXResultHandler {

    private static String apiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";

    private static Logger LOGGER = LoggerFactory.getLogger(JSApiTicket.class);

    private static final String CACHE_KEY = "jsapi_ticket";

    private static final String JS_API_TYPE = "jsapi";

    @Autowired
    private AccessToken accessToken;

    public synchronized final String getTicket() throws WXException {

        String ticket = GuavaCache.getCacheValue(CACHE_KEY);
        if (StringUtils.isEmpty(ticket)) {
            String accessTokenStr = accessToken.getAccessToken();
            final ParaMap pm = ParaMap.create("access_token", accessTokenStr).put("type", JS_API_TYPE);
            JSONObject jsonObject = super.retryDoWXRequest(apiUrl, pm.getData(), 3);
            ticket = jsonObject.getString("ticket");
            GuavaCache.putCache(CACHE_KEY, ticket);
        }
        return ticket;
    }

    @Override
    JSONObject parseResult2Json(String responseString) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("get jsapi_ticket result {}", responseString);
        }
        if (!StringUtils.isEmpty(responseString)) {
            JSONObject jsonObject = JSON.parseObject(responseString);
            int errorCode = jsonObject.getIntValue("errcode");
            if (errorCode == 0) {
                return jsonObject;
            } else {
                LOGGER.warn(" get jsapi_ticket error,result:{}", responseString);
                throw new RuntimeException(" get jsapi_ticket error");
            }
        } else {
            throw new RuntimeException(" get jsapi_ticket error");
        }

    }

}
